package it.struts.helloworld.action;


import it.struts.helloworld.dao.LoginDAO;
import it.struts.helloworld.form.LoginForm;
import it.struts.helloworld.model.Utenti;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;


public class LoginAction extends Action {
	
	private Logger LOG = Logger.getLogger(LoginAction.class);
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
    
    
    
    
            throws Exception {
     
			        String target = null;
			        LoginForm loginForm = (LoginForm)form;
			        
			        LoginDAO login = new LoginDAO();
			        Utenti utente = login.retrieveDetailsDao(loginForm.getUserName(), loginForm.getPassword());
			     
			        try{
			        	LOG.debug("entro nel try");
			        
			        if(loginForm.getUserName().equals(utente.getUsername())
			                && loginForm.getPassword().equals(utente.getPassword())) {
			            
			        	LOG.debug("entro nell'if");
			        	
			            request.setAttribute("ruolo", utente.getTipo());
			            if(request.getAttribute("ruolo").equals("Utente")){
			            	target = "successUser";
			            	
			            	
			            }
			            else if(request.getAttribute("ruolo").equals("Admin")){
			            	target = "successAdm";
			            }
			            else{
			            	target = "successGest";
			            }
			            request.setAttribute("user", utente.getUsername());
			        }
			        } 
			        
			        catch (Exception exep){
			        	target = "failure";
			            request.setAttribute("us", "Le credenziali sono errate!");
						exep.printStackTrace();
						 
					}
					
			       
			        
			        return mapping.findForward(target);
    } 

}